import React, { Component } from "react";
import { connect } from "react-redux";
import { androidBridge, iosBridge } from "./WebViewJavascriptBridge";
import { getAppPlatformsDatas } from "../../Redux/Action/nativeDatas/nativeDatas";
import "./IndexPage.scss";
import { channelCode, version } from "../../config/Config";
import yhTools from "../../tools/yh";
import { redRainUrl } from "@/tools/utils";
import qs from "qs";

class IndexPage extends Component {
	componentDidMount() {
		if (yhTools.platform() == "web") {
			/**前端模拟数据 */
			this.props._getAppPlatformsDatas({
				authHeaderStr:
					'{"userToken":"TOKEN_8ecb4ed7f61546638fca101d88b1395f","sign":"L/7EIQI1GLaZqEnNaOTPFTQzCi4fMpAAHCbENYCYbYt6WM7Ff2sgPEWh7Bv270e2NHSiTdLGgTYZqmRXT5ysPyf56Njwz7rp5bm/ACP+m+QmaGrm0KySB2Y/m4uaqSsK+80nA1BFbybMOAVCNJ267YkVRkuHlnjX7ItC7yLPkYl+qe0IYkBj2dFW/F9TT73HWDt5Ewf9lsffKKY/DcO9eQZLBdw3F7C6kkH8YU6Tri6e0FpnCtxYL1sXwUBg4HKqHEHlWwb+PO2GHfhYJR0LVgsxNtMDjOt4eSyRjZsb8wU+uR/AyC4mhkeFpNLC+GjoVg8OyjKSJiu7szjSBqrY6g==","data":"ONtdVBytNOjdYeVXENGV2VRMRff2+ni2t5+TMkwB0nhANSwf2WLg2x0ext9rROk0lBQLPLAebiu6JzmrHHzgLg4RBhJ2UtCBEsi+Hd4lXPGvJVgVhk/ufbIgc5Z5hdIYTce/HfVDFuofznj1bp7MN58MQ6CqYiNlIl4jQhO6Vl1dN6U879hkj1h5pTNANg+o9VEKEYjJtZE9lH5CoCHte5AjX3Y2EG1m/bTsG7FNiFRP4vDeq6X3Oxl2dRT09OXUyQnz9z4hVySsXj/CcYNmLnCnrlBoSl/laD41asLDiKIevisZggSr2kU5pydYk7C3ycbRTYAClYl9nmOFZtdbFw==","userId":"563830322218362860","merchantId":"LT100100","extendJson":"","mobile":"18996657240","clientCode":"05","plateform":"IOS"}',
				applyNo: "01", // 申请编号
				lnid: "1", // 产品编号
				orderCode: "123456789", // 订单编号
				orderName: "测试订单", // 订单名称
				payAmount: "100", // 支付金额
				orderAmount: "100", // 订单金额
				mobile: "18996657240", // 注册手机号
				pageType: "616", // 页面类型
				devicesInfo: {
					androidId: "5e02fe4a-72ff-3979-b452-c1957d9244ea",
					uuid: "cc41667e8bbb5ea1",
					deviceId: "5e02fe4a-72ff-3979-b452-c1957d9244ea"
				},
				httpUrl:
					"https://jrpay-front-service-dev-jr.yonghui.cn/LoanFrontService"
			});
			this.goToPage();
		} else if (yhTools.platform() == "ios") {
			let _that = this;
			iosBridge(function (bridge) {
				window.YHAuthorize = bridge;
				//初始化事件
				_that.initDatas();
				//从native获取数据
				_that.getFromNative();
			});
		} else if (yhTools.platform() == "android") {
			let _that = this;
			androidBridge();
			this.connectWebViewJavascriptBridge(function (bridge) {
				window.YHAuthorize = bridge;
				window.YHAuthorize.init(function (message, responseCallback) {
					responseCallback();
				});
				//初始化事件
				_that.initDatas();
				//从native获取数据
				_that.getFromNative();
			});
		}
	}

	//初始化事件
	initDatas() {
		// 初始化事件
		window.YHAuthorize.View = document.createElement("BUTTON");
		window.YHAuthorize.registerEvent = function (type, data) {
			let event = document.createEvent("Events");
			event.initEvent(type, false, false);
			if (data) {
				for (let i in data) {
					if (data.hasOwnProperty(i)) {
						event[i] = data[i];
					}
				}
			}
			window.YHAuthorize.View.dispatchEvent(event);
		};
		// 全局添加意见反馈监听
		let _that = this;
		window.YHAuthorize.View.addEventListener("FeedBackListener", res => {
			_that.props._getAppPlatformsDatas({
				feedBack: res
			});
			window.location.replace("#/FeedBackKind");
		});
	}

	connectWebViewJavascriptBridge(callback) {
		if (window.WebViewJavascriptBridge) {
			callback(window.WebViewJavascriptBridge);
		} else {
			document.addEventListener(
				"WebViewJavascriptBridgeReady",
				function () {
					callback(window.WebViewJavascriptBridge);
				},
				false
			);
		}
	}
	/**从app的native的拿到数据到存储到props */
	getFromNative() {
		let _that = this;
		let _tempMutDic = "";
		const clientCodeObj = qs.parse(location.search.slice(1));
		new Promise(resolve => {
			window.YHAuthorize.callHandler("Sdk_init", "", res => {
				console.log(res);
				if (res.status == "1000") {
					let {
						page_type,
						merchant_id,
						user_id,
						sign,
						data,
						mobile,
						extend_json,
						order_code,
						order_name,
						order_amount,
						pay_amount,
						user_token,
						lnid,
						payCouponList,
						payCoupon,
						sdkVersionCode = "1.0.0"
					} = res.data;
					// 神策登录
					_yh.sa.login(mobile);
					version.sdkVersionCode = sdkVersionCode;
					let authHeaderStr = JSON.stringify({
						userToken: user_token, // 用户token
						sign, // 签名数据
						data, // 加签的数据
						userId: user_id, // 用户id
						merchantId: merchant_id, // 商户号
						extendJson: extend_json, // 扩展数据
						mobile: mobile, // 注册手机号
						clientCode: clientCodeObj.clientCode || "05",
						plateform: yhTools.platform() === "ios" ? "IOS" : "Android" //平台类型
					});
					window.localStorage.wmUserInfo = JSON.stringify({
						userId: mobile,
						userTag: "life",
						projectVersion: "1.0.0"
					});
					_that.props._getAppPlatformsDatas({
						authHeaderStr, // 请求头
						lnid: lnid, // 产品编号
						orderCode: order_code, // 订单编号
						orderName: order_name, // 订单名称
						payAmount: pay_amount, // 支付金额
						orderAmount: order_amount, // 订单金额
						mobile, // 注册手机号
						pageType: page_type, // 页面类型
						httpUrl: res.httpUrl, // 接口请求前缀
						payCouponList,
						payCoupon,
						sdkVersionCode,
						userId: user_id,
						extJsonStr: res.extJsonStr
					});
					if (yhTools.platform() == "ios") {
						_tempMutDic = res.data.mutDic;
					} else if (res.data.mutDic) {
						_tempMutDic = JSON.parse(res.data.mutDic);
					}
					if (_tempMutDic == "") {
						_tempMutDic = {};
					}
				}
				resolve();
			});
		}).then(() => {
			window.YHAuthorize.callHandler("Device_Environment", "", resp => {
				//获取设备信息
				let isIphone = false;
				if (resp.data.isHair == "1") {
					isIphone = true;
				} else {
					isIphone = false;
				}
				_that.props._getAppPlatformsDatas({
					channelCode: channelCode,
					phoneX: isIphone,
					mutDic: { phoneX: isIphone }, //手机类型
					openId: "",
					unionid: "",
					devicesInfo: resp.data, // 设备信息
					appVersion: version.versionName, //App版本号
					deviceVersion: resp.data.system_version, //系统版本
					plateform: resp.data.system_name, //Android，iOS
					deviceId:
						resp.data.system_name == "iOS" ? resp.data.idfa : resp.data.uuid, //UUID
					macAddress: resp.data.wifi_mac, //wifiMac
					batteryCapacity: resp.data.battery_level //电池电量
				});
				if (!_tempMutDic) {
					_tempMutDic = {};
				}
				_tempMutDic.phoneX = isIphone;
				_that.goToPage(); // 跳转到不同的页面
			});
		});
	}
	/**根据页面类型跳转到不同的页面 */
	goToPage() {
		setTimeout(() => {
			let pageType = this.props.getAppPlatformsDatas.pageType;
			console.log(
				"this.props.getAppPlatformsDatas--->",
				this.props.getAppPlatformsDatas
			);
			console.log("pageType--->", pageType);
			// 此处pageType不要写死
			// this.props.history.push("/newPersonCoupon");
			switch (pageType) {
				case "pageBalance": // 余额首页
					sessionStorage.setItem("index_fromType", "app");
					this.xhfdJumpPage("xhqbrecharge");
					break;
				case "pageXiaoHuiBao": // 小辉宝首页
					this.xhfdJumpPage("walletHome");
					break;
				case "pageXhfIsCredit": // 小辉付首页-已授信（申请入口:我的）
					this.props.history.push({
						pathname: "/xhfHomeCredit",
						state: {
							from: "我的"
						}
					});
					break;
				case "pageXhfIsNotCredit": // 小辉付首页-未授信（申请入口:我的）
					this.props.history.push({
						pathname: "/xhfHomeNoCredit",
						state: {
							from: "我的"
						}
					});
					break;
				case "pageXhfCrediting": // 小辉付首页-授信中（申请入口:我的）
					this.xhfdJumpPage("xhfHomeCrediting");
					break;
				case "pagePayXhfCrediting": // 小辉付首页-授信中（申请入口:收银台）
					this.xhfdJumpPage("xhfHomeCrediting");
					break;
				case "pagePayXhfNotCredit": // 小辉付首页-未授信（申请入口:收银台）
					this.props.history.push({
						pathname: "/xhfHomeNoCredit",
						state: {
							from: "收银台"
						}
					});
					break;
				case "pageXiaoHuiLoan": // 小辉贷首页
					this.xhfdJumpPage("xhdHome");
					break;
				case "pageXiaoHuiMoney": // 小辉钱包
					this.xhfdJumpPage("xhqbIndex");
					break;
				case "pageXiaoHuiPayContract": // 小辉付签协议
					this.props.history.push({
						pathname: `/myProtocolList`,
						query: { name: "index" }
					});
					break;
				case "pageXiaoHuiPaySetPwd": // 小辉付设置密码
					this.props._getAppPlatformsDatas({
						isFromPayMoney: true
					});
					this.xhfdJumpPage("xhfSetPasswordPage");
					break;
				case "xhfPay": // 小辉付支付码
					this.props.history.replace({
						pathname: `/payCode`,
						state: { type: "index" }
					});
					break;
				case "pageXiaoHuiLoanInfoSuccess": // 小辉贷资料提交成功页
					this.xhfdJumpPage("xhfOpenSuccess");
					break;
				case "pageXiaoHuiLoanFail": // 小辉贷开通失败页
					this.xhfdJumpPage("xhdOpenFail");
					break;
				case "btnAddBank": // 小辉钱包添加银行卡
					this.props.history.replace({
						pathname: `/xhqbAddBank`,
						state: { type: "closeApp" }
					});
					break;
				case "pageXiaoHuiBaoPaySign": // 小辉宝签约支付
					sessionStorage.setItem("index_fromType", "app");
					this.xhfdJumpPage("signXHB");
					break;
				case "pageXiaoHuiBaoRecharge": // 小辉宝充值
					sessionStorage.setItem("index_fromType", "app");
					this.xhfdJumpPage("rechargeAccount");
					break;
				case "pageBank": // 银行卡管理
					sessionStorage.setItem("index_fromType", "app");
					this.props.history.push({ pathname: "/bankManageList" });
					break;
				/* case "pageCoupleCenter": // 领券中心
					sessionStorage.setItem("index_fromType", "app");
					this.props.history.push({ pathname: "/couponCenter" });
					break; */
				case "pageCoupleCenter": // 之前的领券中心-》现在的支付优惠
					this.props.history.push({ pathname: "/paymentDiscount/index" });
					break;
				case "pageSelectCouple": // 选择使用的优惠券
					this.props.history.push({ pathname: "/selectCoupon" });
					break;
				case "pageXiaoHuiPayActive": // 小辉付激活页
					this.props._getAppPlatformsDatas({
						isFromPayMoney: true
					});
					this.props.history.push({
						pathname: "/xhfFacilitySuccess"
					});
					break;
				case "612": // 三要素认证
					this.xhfdJumpPage("certification/612");
					break;
				case "613": // 二要素
					this.xhfdJumpPage("certification/613");
					break;
				case "616": // 616流程 三要素认证+邀请码
					this.xhfdJumpPage("creditExtension/616/threeElements");
					break;
				case "pagePaytoolV2": // 新收银台
					this.xhfdJumpPage("wallet");
					break;
				case "pageSytClickXhb": // 快捷支付列表里面的小辉宝支付
					this.props.history.push({
						pathname: "/fastPayment/payConfirm",
						query: {
							payScene: "IPAY",
							from: "pageSytClickXhb"
						}
					});
					break;
				case "pageOfflinePayTool": // 新收银台
					this.props.history.push({
						pathname: "/memberCodeWallet",
						query: {
							payScene: "MPAY"
						}
					});
					break;
				case "pageNewActionPage": // 双12活动页面
					this.props.history.push({ pathname: "/dTwelveActivities" });
					break;
				case "pageRedRain": // 红包雨
					sessionStorage.setItem("index_fromType", "app");
					this.props.history.push({
						pathname: "/iframePage",
						state: {
							title: "",
							src: redRainUrl()
						}
					});
					break;
				case "pageCheckStand": // 彩食鲜收银台
					this.props.history.push({ pathname: "/shopWallet" });
					break;
				case "pageXhdBill": // 小辉贷账单页
					this.xhfdJumpPage("xhdPayBackHome");
					break;
				case "pageXhfBill": // 小辉付账单页
					this.xhfdJumpPage("billHome");
					break;
				case "pageXhfBankCard": //银行卡管理
					this.xhfdJumpPage("bankManageList");
					break;
				case "pageHjIdCard": //好借授信开通-身份认证页面
					this.xhfdJumpPage("xhd/credit/authentication");
					break;
				case "pageHjApply": //好借借款申请页面
					this.xhfdJumpPage("xhdHome");
					break;
				case "pageHjRecord": //好借借款记录页
					this.xhfdJumpPage("xhdRecordList");
					break;
				case "pageXhfPromotion": //推广有礼
					this.xhfdJumpPage("inviteHome");
					break;
				case "pageXhfNewZone": //新手专区
					this.xhfdJumpPage("newbornZone");
					break;
				case "pageXhfCommonProblem": //常见问题
					this.xhfdJumpPage("allQuestion");
					break;
				case "pageNotSignPay": // 余额支付未签约
					this.xhfdJumpPage("xhbBalanceAccountOpened");
					break;
				case "pageInSignPay": // 余额支付签约中
					this.xhfdJumpPage("xhbBalanceInSign");
					break;
				case "pageIsSignPay": // 余额支付已签约
					this.xhfdJumpPage("xhbBalanceAccountOpened");
					break;
				case "pageOpenEAccount": // 余额支付开通电子账户
					this.xhfdJumpPage("xhbBalanceNoAccount");
					break;
				case "pageQuickSign": // 快捷支付确认支付页面
					this.props.history.push({
						pathname: "/fastPayment/payConfirm",
						query: {
							payScene: "IPAY"
						}
					});
					break;
				case "pageOfflinePayToolQuickSign": // 线下会员码过来-快捷支付确认支付页面
					this.props.history.push({
						pathname: "/fastPayment/payConfirm",
						query: {
							payScene: "MPAY"
						}
					});
					break;
				case "pageQuickSignBind": // 快捷支付绑卡页面-(入口：收银台)
					this.props.history.push({
						pathname: "/fastPayment/bindCard",
						query: {
							from: "cashier"
						}
					});
					break;
				case "pageShQuickSignApply": // 快捷支付绑卡页面-（入口：会员码）
					this.props.history.push({
						pathname: "/fastPayment/bindCard",
						query: {
							from: "membershipCode"
						}
					});
					break;
				case "pageSxSecurity": // 山西证券
					this.xhfdJumpPage("advertising/sSecurity/index");
					break;
				case "pageArgeement": // 我的协议列表
					this.props.history.push({
						pathname: "/myAgreement"
					});
					break;
				case "pageXhdOpenResult": // 贷拉付，贷被拒，付通过
					this.props.history.push({
						pathname: "/xhdOpenXhfSuccess"
					});
					break;
				default:
					// 页面未找到
					this.xhfdJumpPage("error404");
					break;
			}
		});
	}

	//小辉付,小辉贷跳转不同首页
	xhfdJumpPage(url, data) {
		this.props.history.push({
			pathname: `/${url}`,
			state: data
		});
	}

	render() {
		return <div></div>;
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_getAppPlatformsDatas: abj => {
			//获取native的数据
			dispatch(getAppPlatformsDatas(abj));
		}
	};
}

export default connect(mapStateToProps, mapDispatchToProps)(IndexPage);
